import React, { useState, useEffect } from 'react';
import { 
  Typography, Row, Col, Card, Button, Statistic, Divider,
  Tag, Breadcrumb, Empty, Spin, Progress, message, Modal, InputNumber, List, Avatar
} from 'antd';
import { Link, useParams } from 'react-router-dom';
import { 
  ThunderboltOutlined, 
  ClockCircleOutlined,
  ShoppingCartOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';

const { Title, Paragraph, Text } = Typography;
const { Countdown } = Statistic;
const { confirm } = Modal;

// 复用上一个页面的模拟数据
const mockActivities = [
  {
    id: 1,
    name: '618电子产品大促',
    description: '年中大促，电子产品限时秒杀，错过等一年',
    startTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2小时前开始
    endTime: new Date(Date.now() + 22 * 60 * 60 * 1000).toISOString(), // 22小时后结束
    status: 'active',
    banner: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBNWAGaRsAAWgzJ8SrKo845.jpg',
    rules: [
      '每个账号限购1件同款商品',
      '秒杀商品不支持使用优惠券',
      '秒杀商品不支持无理由退换',
      '付款后24小时内发货',
      '数量有限，先到先得'
    ],
    products: [
      {
        id: 1,
        productId: 1,
        name: 'iPhone 13 Pro',
        originalPrice: 7999,
        seckillPrice: 6999,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLe2mALDSVAAF0enjwEQA837.jpg',
        stock: 50,
        limitPerUser: 1,
        sold: 30,
        description: 'A15仿生芯片，超瓷晶面板，专业级摄像系统',
        features: ['6.1英寸显示屏', 'A15仿生芯片', '三摄系统', '钢化玻璃']
      },
      {
        id: 2,
        productId: 6,
        name: 'Switch游戏机',
        originalPrice: 2099,
        seckillPrice: 1799,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLeviAFdHhAAErLFJZZsg037.jpg',
        stock: 100,
        limitPerUser: 1,
        sold: 60,
        description: '任天堂便携式游戏机，可支持多种游戏模式',
        features: ['便携式设计', '多种游戏模式', '双手柄', '大量独占游戏']
      }
    ]
  },
  {
    id: 2,
    name: '新品首发特惠',
    description: '最新上市产品限时优惠',
    startTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(), // 2天后开始
    endTime: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000).toISOString(), // 4天后结束
    status: 'upcoming',
    banner: 'https://img01.71360.com/file/read/www/M00/4C/A4/wKj0iWTRBciAZE4sAAMcOqL_5Pg877.jpg',
    rules: [
      '每个账号限购1件同款商品',
      '秒杀商品不支持使用优惠券',
      '付款后24小时内发货',
      '数量有限，先到先得'
    ],
    products: [
      {
        id: 3,
        productId: 5,
        name: 'iPad Air',
        originalPrice: 4799,
        seckillPrice: 4299,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/23/wKj0iWTLerqAHFU8AAFoT7tZJb4297.jpg',
        stock: 30,
        limitPerUser: 1,
        sold: 0,
        description: '搭载M1芯片的全新iPad Air，轻薄便携',
        features: ['10.9英寸显示屏', 'M1芯片', 'USB-C接口', '支持二代Apple Pencil']
      },
      {
        id: 4,
        productId: 8,
        name: 'Apple Watch Series 7',
        originalPrice: 3199,
        seckillPrice: 2799,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLevSAQ6U3AAFZZzAuwUg396.jpg',
        stock: 50,
        limitPerUser: 1,
        sold: 0,
        description: '更大的显示屏，更快的充电速度，更强的耐用性',
        features: ['始终显示视网膜屏幕', '防尘防水', '血氧监测', '心电图功能']
      }
    ]
  },
  {
    id: 3,
    name: '5月数码大促',
    description: '数码产品折扣季',
    startTime: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10天前开始
    endTime: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), // 5天前结束
    status: 'ended',
    banner: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBQuAYjZtAAIUwpCOQtE413.jpg',
    rules: [
      '每个账号限购2件同款商品',
      '秒杀商品不支持使用优惠券',
      '付款后24小时内发货'
    ],
    products: [
      {
        id: 5,
        productId: 3,
        name: '小米手环7',
        originalPrice: 249,
        seckillPrice: 199,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4D/59/wKj0iGTcxUmAQwAGAAF_rOyZvxw488.jpg',
        stock: 200,
        limitPerUser: 2,
        sold: 200,
        description: '彩色AMOLED大屏，14天超长续航',
        features: ['彩色显示屏', '心率监测', '睡眠监测', '防水50米']
      }
    ]
  }
];

const SeckillDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(true);
  const [activity, setActivity] = useState<any>(null);
  const [quantities, setQuantities] = useState<{[key: number]: number}>({});

  useEffect(() => {
    // 模拟数据加载
    setLoading(true);
    setTimeout(() => {
      const foundActivity = mockActivities.find(a => a.id === parseInt(id || '0', 10));
      setActivity(foundActivity || null);
      
      // 初始化所有商品的数量为1
      if (foundActivity) {
        const initialQuantities: {[key: number]: number} = {};
        foundActivity.products.forEach(product => {
          initialQuantities[product.id] = 1;
        });
        setQuantities(initialQuantities);
      }
      
      setLoading(false);
    }, 500);
  }, [id]);

  const handleQuantityChange = (productId: number, value: number | null) => {
    setQuantities({
      ...quantities,
      [productId]: value || 1
    });
  };

  const handleAddToCart = (product: any) => {
    if (activity.status !== 'active') {
      message.warning('该秒杀活动未开始或已结束');
      return;
    }

    if (product.stock <= 0) {
      message.error('该商品已售罄');
      return;
    }

    const quantity = quantities[product.id] || 1;
    
    if (quantity > product.limitPerUser) {
      message.warning(`该商品每人限购${product.limitPerUser}件`);
      return;
    }

    message.success(`已将 ${quantity} 件 ${product.name} 加入购物车`);
  };

  const handleBuyNow = (product: any) => {
    if (activity.status !== 'active') {
      message.warning('该秒杀活动未开始或已结束');
      return;
    }

    if (product.stock <= 0) {
      message.error('该商品已售罄');
      return;
    }

    const quantity = quantities[product.id] || 1;
    
    if (quantity > product.limitPerUser) {
      message.warning(`该商品每人限购${product.limitPerUser}件`);
      return;
    }

    confirm({
      title: '确认购买',
      icon: <ExclamationCircleOutlined />,
      content: `确定立即购买 ${quantity} 件 ${product.name}？`,
      onOk() {
        message.success('下单成功，即将跳转到支付页面');
        // 这里实际项目中应该跳转到订单确认页面
      }
    });
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!activity) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Empty description="未找到该秒杀活动" />
        <Button type="primary" style={{ marginTop: 16 }}>
          <Link to="/seckill">返回秒杀列表</Link>
        </Button>
      </div>
    );
  }

  return (
    <div className="seckill-detail-page">
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/seckill">秒杀活动</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>{activity.name}</Breadcrumb.Item>
      </Breadcrumb>
      
      <div>
        <Card 
          style={{ marginBottom: 24 }}
          cover={
            <img 
              alt={activity.name} 
              src={activity.banner} 
              style={{ height: 200, objectFit: 'cover' }}
            />
          }
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <Title level={3} style={{ margin: 0 }}>{activity.name}</Title>
            <Tag color={
              activity.status === 'active' ? 'green' : 
              activity.status === 'upcoming' ? 'blue' : 'red'
            }>
              {activity.status === 'active' ? '进行中' : 
               activity.status === 'upcoming' ? '即将开始' : '已结束'}
            </Tag>
          </div>
          
          <Paragraph>{activity.description}</Paragraph>
          
          <div style={{ marginBottom: 16 }}>
            {activity.status === 'active' && (
              <div>
                <ClockCircleOutlined /> 距结束: 
                <Countdown 
                  value={new Date(activity.endTime).getTime()} 
                  format="D 天 H 时 m 分 s 秒"
                  style={{ marginLeft: 8 }}
                />
              </div>
            )}
            
            {activity.status === 'upcoming' && (
              <div>
                <ClockCircleOutlined /> 距开始: 
                <Countdown 
                  value={new Date(activity.startTime).getTime()} 
                  format="D 天 H 时 m 分 s 秒"
                  style={{ marginLeft: 8 }}
                />
              </div>
            )}
          </div>
        </Card>
        
        <Card title="活动规则" style={{ marginBottom: 24 }}>
          <List
            dataSource={activity.rules}
            renderItem={(rule: string) => (
              <List.Item>
                <Text>• {rule}</Text>
              </List.Item>
            )}
          />
        </Card>
        
        <Title level={4}>秒杀商品</Title>
        
        <List
          itemLayout="vertical"
          dataSource={activity.products}
          renderItem={(product: any) => {
            const soldOutPercentage = (product.sold / (product.stock + product.sold)) * 100;
            const isProductAvailable = activity.status === 'active' && product.stock > 0;
            
            return (
              <Card style={{ marginBottom: 16 }}>
                <List.Item
                  key={product.id}
                  extra={
                    <img 
                      width={200} 
                      alt={product.name}
                      src={product.imageUrl}
                    />
                  }
                >
                  <List.Item.Meta
                    title={<Title level={4}>{product.name}</Title>}
                    description={
                      <div>
                        <div style={{ marginBottom: 8 }}>
                          <Text delete style={{ marginRight: 8 }}>原价: ¥{product.originalPrice}</Text>
                          <Text type="danger" style={{ fontSize: 20, fontWeight: 'bold' }}>秒杀价: ¥{product.seckillPrice}</Text>
                          <Tag color="red" style={{ marginLeft: 8 }}>
                            {((product.originalPrice - product.seckillPrice) / product.originalPrice * 100).toFixed(0)}% 折扣
                          </Tag>
                        </div>
                        <Paragraph>{product.description}</Paragraph>
                      </div>
                    }
                  />
                  
                  <div style={{ marginTop: 16, marginBottom: 16 }}>
                    <div style={{ display: 'flex', gap: '8px', marginBottom: 8 }}>
                      {product.features.map((feature: string, index: number) => (
                        <Tag key={index}>{feature}</Tag>
                      ))}
                    </div>
                  </div>
                  
                  <div style={{ marginBottom: 16 }}>
                    <Text type="secondary">每人限购 {product.limitPerUser} 件</Text>
                    {activity.status !== 'upcoming' && (
                      <div style={{ marginTop: 8 }}>
                        <Text>已售 {product.sold} / 限量 {product.stock + product.sold}</Text>
                        <Progress percent={soldOutPercentage} showInfo={false} />
                      </div>
                    )}
                  </div>
                  
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    <div>
                      <Text style={{ marginRight: 8 }}>数量:</Text>
                      <InputNumber 
                        min={1} 
                        max={Math.min(product.limitPerUser, product.stock)} 
                        defaultValue={1}
                        value={quantities[product.id] || 1}
                        onChange={(value) => handleQuantityChange(product.id, value)}
                        disabled={!isProductAvailable}
                      />
                    </div>
                    
                    <Button
                      type="default"
                      icon={<ShoppingCartOutlined />}
                      disabled={!isProductAvailable}
                      onClick={() => handleAddToCart(product)}
                    >
                      加入购物车
                    </Button>
                    
                    <Button
                      type="primary"
                      danger
                      disabled={!isProductAvailable}
                      onClick={() => handleBuyNow(product)}
                    >
                      {activity.status === 'active' ? '立即抢购' : 
                       activity.status === 'upcoming' ? '即将开始' : '已结束'}
                    </Button>
                  </div>
                  
                  {product.stock <= 0 && activity.status === 'active' && (
                    <div style={{ marginTop: 16 }}>
                      <Tag color="red">已售罄</Tag>
                    </div>
                  )}
                </List.Item>
              </Card>
            );
          }}
        />
      </div>
    </div>
  );
};

export default SeckillDetailPage; 